import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:test_flutter/entity/todo_item.dart';
import 'package:test_flutter/entity/user_item.dart';
import 'package:test_flutter/util/db_utils.dart';
import 'package:test_flutter/util/shared_preferences_utils.dart';

///sqflite：轻巧的数据库，支持原生数据库大多数功能
///SP：KEY-VALUE格式的数据存储方案，原子型
///Bloc：状态管理方案，APP一旦关闭，其状态就会丢失；但在使用期间，状态时可以实时更新，跨页面，跨组件同步更新的
///Hive：集成三者有点，一站式解决了数据库持久存储和实时响应的问题，注意存储数据应该在1000~5000左右，超过这个值，
///      性能会降低，可以加索引的方式处理
///Box：数据存放在box中，类似数据库中的Table，但在HIVE中，可以直接使用Box操作数据，比如Box.add,Box.delete等。
///Object：类似数据库中的Entity(实体)。Hive可以存储绝大多数的数据类型，例如:Box.add('小米'),Box.put('platform','android'),
///        如果需要存储复杂的数据，需要自定义一个对象，对象需要继承HiveObject
///Adapter：自定义对象的适配器，需要实现typeId,read和write。
///
class StorePage extends StatefulWidget {
  @override
  // State<StatefulWidget> createState() => _HivePageState();
  // State<StatefulWidget> createState() => _HiveAdapterState();
  State<StatefulWidget> createState() => _SharedPreferencesState();
}

class _SharedPreferencesState extends State<StorePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hive数据库'),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextButton(
              onPressed: () async {
                await SharedPreUtils.setSN(
                    '${DateTime.now().microsecondsSinceEpoch}');
                setState(() {});
              },
              child: Text('set SN'),
            ),
            TextButton(
              onPressed: () async {
                await SharedPreUtils.setUserInfo('张三，18岁');
                setState(() {});
              },
              child: Text('set User'),
            ),
            Text(
                'SN:${SharedPreUtils.getSN()}, user:${SharedPreUtils.getUserInfo()}')
          ],
        ),
      ),
    );
  }
}

class _HiveAdapterState extends State<StorePage> {
  late DBUtils _dbUtils;
  int index = 0;

  @override
  void initState() {
    init();
    super.initState();
  }

  Future<void> init() async {
    _dbUtils = await DBUtils.getInstance();
    print('init mounted:$mounted');
    if (!mounted) return;
    setState(() {
      index = _dbUtils.todoBox.length;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hive数据库'),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextButton(
              onPressed: () async {
                await _dbUtils.todoBox.add(TodoItem(
                    content: '欢迎${++index}',
                    level: index,
                    createAt: '${DateTime.now().microsecondsSinceEpoch}',
                    completionAt: '${DateTime.now().microsecondsSinceEpoch}'));
                setState(() {
                  for (dynamic item in _dbUtils.todoBox.values) {
                    print('$item');
                  }
                });
              },
              child: Text('add'),
            ),
            TextButton(
              onPressed: () async {
                if (_dbUtils.todoBox.isNotEmpty) {
                  print('isOpen:${Hive.box('todo').isOpen}');
                  await Hive.box('todo').clear();
                  setState(() {
                    index = 0;
                  });
                }
              },
              child: Text('clean'),
            ),
            TextButton(
              onPressed: () async {
                await _dbUtils.todoBox.close();
                setState(() {});
              },
              child: Text('close'),
            ),
            TextButton(
              onPressed: () async {
                _dbUtils.todoBox = await Hive.openBox('todo');
                setState(() {});
              },
              child: Text('open'),
            ),
            TextButton(
              onPressed: () async {
                await _dbUtils.todoBox.put(
                    'device_id', 'SN:${DateTime.now().microsecondsSinceEpoch}');
                setState(() {
                  print('todo:${_dbUtils.todoBox.toMap()}');
                });
              },
              child: Text('add key'),
            ),
            TextButton(
              onPressed: () async {
                print(
                    'has: ${_dbUtils.todoBox.containsKey('device_id')}, get:${_dbUtils.todoBox.get('device_id', defaultValue: 'device_id is NULL')}');
                if (_dbUtils.todoBox.containsKey('device_id')) {
                  await _dbUtils.todoBox.delete('device_id');
                }
              },
              child: Text('delete key'),
            ),
            TextButton(
              onPressed: () async {
                print('add user start...');
                await _dbUtils.userBox.add(UserInfo(name: '张三', age: 10));
                print('add user box:${_dbUtils.userBox.toMap()}');
              },
              child: Text('add user'),
            ),
            TextButton(
              onPressed: () async {
                print('delete user start...');
                if (_dbUtils.userBox.isOpen) {
                  if (_dbUtils.userBox.isNotEmpty) {
                    await _dbUtils.userBox.deleteAt(0);
                  }
                  print('delete user box size: ${_dbUtils.userBox.length}');
                }
              },
              child: Text('delete user'),
            ),
            Text('count:${_dbUtils.todoBox.length}')
          ],
        ),
      ),
    );
  }
}

class _HivePageState extends State<StorePage> {
  late DBUtils _dbUtils;

  @override
  void initState() {
    init();
    super.initState();
  }

  Future<void> init() async {
    _dbUtils = await DBUtils.getInstance();
    print('init mounted:$mounted');
    if (!mounted) return;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hive数据库'),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            InkWell(
              onTap: () async {
                await _dbUtils.tagBox
                    .add("time:${DateTime.now().microsecondsSinceEpoch}");
                setState(() {});
              },
              child: Text('add'),
            ),
            InkWell(
              onTap: () async {
                if (_dbUtils.tagBox.isNotEmpty) {
                  await _dbUtils.tagBox.deleteAt(0);
                  setState(() {});
                }
              },
              child: Text('delete'),
            ),
            Text('tags:${_dbUtils.tagBox.toMap()}')
          ],
        ),
      ),
    );
  }
}
